package com.cade.agriculturemall.view.classify.goodsdetail;

import android.content.Context;

import com.avos.avoscloud.AVCloudQueryResult;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.AVSaveOption;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.CloudQueryCallback;
import com.avos.avoscloud.DeleteCallback;
import com.avos.avoscloud.FindCallback;
import com.avos.avoscloud.GetCallback;
import com.avos.avoscloud.SaveCallback;
import com.cade.agriculturemall.R;
import com.cade.agriculturemall.base.BasePresenter;
import com.cade.agriculturemall.model.ClassifyEntity;
import com.cade.agriculturemall.model.GoodsDetailEntity;
import com.cade.agriculturemall.model.ShoppingCarsEntity;
import com.cade.agriculturemall.model.UserInfoEntity;

import java.util.List;

/**
 * Created by Lobby on 2017/11/22.
 */

public class GoodsDetailPresenter extends BasePresenter<GoodsDetailContract.IView> implements GoodsDetailContract.IPresenter {
    private GoodsDetailEntity entity = new GoodsDetailEntity();
    private String itemFavouriteId;
    private String currentUserId;
    final UserInfoEntity user = AVUser.getCurrentUser(UserInfoEntity.class);
    private String name;


    public GoodsDetailPresenter(GoodsDetailContract.IView view) {
        super(view);
    }

    @Override
    public void onResume() {

    }

    @Override
    public void onCreate() {

    }

    @Override
    public void onDestroy() {

    }

    /**
     * 获取商品信息
     *
     * @param objectId
     */
    @Override
    public void getGoodsDetail(String objectId) {
        mView.showProgress();
        AVUser.alwaysUseSubUserClass(UserInfoEntity.class);
        currentUserId = user.getObjectId();
        AVQuery<GoodsDetailEntity> avQuery = new AVQuery<>("ClassifyGoodsThird");
//        avQuery.orderByDescending("createAt");
        avQuery.whereEqualTo("objectId", objectId);
        avQuery.getFirstInBackground(new GetCallback<GoodsDetailEntity>() {
            @Override
            public void done(GoodsDetailEntity goodsDetailEntity, AVException e) {
                if (e == null) {
                    entity = goodsDetailEntity;
                    mView.setEntity(goodsDetailEntity);
                    // 存储成功
                } else {
                    // 失败的话，请检查网络环境以及 SDK 配置是否正确
                    e.printStackTrace();
                }
                mView.dismissProgress();
            }
        });
    }

    /**
     * 查询是否已收藏
     *
     * @param goodsDetailEntity
     * @param listener
     */
    @Override
    public void isLike(GoodsDetailEntity goodsDetailEntity, final GoodsDetailContract.ProductLikeListener listener) {
        if (goodsDetailEntity != null) {
            AVQuery<AVObject> myItemFavourite = new AVQuery<>("ItemFavourite");
            myItemFavourite.whereEqualTo("pro_Id", goodsDetailEntity);
            myItemFavourite.whereEqualTo("user_Id", currentUserId);
            myItemFavourite.findInBackground(new FindCallback<AVObject>() {
                @Override
                public void done(List<AVObject> list, AVException e) {
                    if (e == null) {
                        if (list.size() != 0) {
                            listener.isProductLike(true);
                        } else {
                            listener.isProductLike(false);
                        }
                    } else {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    /**
     * 判断是否存在购物车内
     *
     * @param goodsDetailEntity
     * @param listener
     */
    @Override
    public void isInShoppingCars(GoodsDetailEntity goodsDetailEntity, final GoodsDetailContract.ProductLikeListener listener) {
        if (goodsDetailEntity != null) {
            AVQuery<AVObject> shoppingCars = new AVQuery<>("ShoppingCars");
            shoppingCars.whereEqualTo("pro", goodsDetailEntity);
            shoppingCars.whereEqualTo("user_Id", currentUserId);
            shoppingCars.whereEqualTo("orderId", null);
            shoppingCars.findInBackground(new FindCallback<AVObject>() {
                @Override
                public void done(List<AVObject> list, AVException e) {
                    if (e == null) {
                        if (list.size() != 0) {
                            listener.isProductLike(true);
                        } else {
                            listener.isProductLike(false);
                        }
                    } else {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    /**
     * 添加进购物车
     */
    @Override
    public void addCars() {
        if (entity != null) {
            final AVObject shoppingCars = new AVObject("ShoppingCars");
            shoppingCars.put("user_Id", currentUserId);
            shoppingCars.put("pro", entity);
            shoppingCars.put("quantitate", 1);
            shoppingCars.put("pro_price", entity.getPriceNew());
            shoppingCars.saveInBackground(new SaveCallback() {
                @Override
                public void done(AVException e) {
                    if (e == null) {
                    }
                }
            });
        }
    }

    /**
     * 添加收藏
     */
    @Override
    public void addFavourite() {
        if (entity != null) {
            final AVObject itemFavourite = new AVObject("ItemFavourite");
            itemFavourite.put("user_Id", currentUserId);
            itemFavourite.put("pro_Id", entity);
            itemFavourite.saveInBackground(new SaveCallback() {
                @Override
                public void done(AVException e) {
                    if (e == null) {
                        mView.showMessage("保存完成");
                        itemFavouriteId = itemFavourite.getObjectId();
                    }
                }
            });
        }
    }

    /**
     * 取消收藏
     */
    @Override
    public void deleteFavourite() {
        if (entity != null) {
            AVQuery<AVObject> deleteFavourite = new AVQuery<>("ItemFavourite");
            deleteFavourite.whereEqualTo("user_Id", currentUserId);
            deleteFavourite.whereEqualTo("pro_Id", entity);
            deleteFavourite.deleteAllInBackground(new DeleteCallback() {
                @Override
                public void done(AVException e) {
                    if (e != null) {
                        mView.showMessage(e.getMessage());
                    }
                }
            });
        }
    }

    /**
     * 删除添加进购物车的商品
     */
    @Override
    public void deleteShoppingCars() {
        if (entity != null) {
            AVQuery<AVObject> deleteShopCar = new AVQuery<>("ShoppingCars");
            deleteShopCar.whereEqualTo("user_Id", currentUserId);
            deleteShopCar.whereEqualTo("pro", entity);
            deleteShopCar.whereEqualTo("shop_Id", entity.getShoper());
            deleteShopCar.deleteAllInBackground(new DeleteCallback() {
                @Override
                public void done(AVException e) {
                    if (e != null) {
                        mView.showMessage(e.getMessage());
                    }
                }
            });
        }

    }

    //       判断是否存历史浏览表中
    public void isinHistory(Context context, String targrtid) {
        if (entity != null) {
            final String name = context.getString(R.string.classHistoryTittle) + currentUserId;
            final String objectId = targrtid;
            final AVQuery<AVObject> queryHistory = new AVQuery<>(name);
            queryHistory.whereEqualTo("proId", objectId);
            String te = entity.getObjectId();
            queryHistory.findInBackground(new FindCallback<AVObject>() {
                @Override
                public void done(List<AVObject> list, AVException e) {
                    if (e == null) {
                        final AVObject todoFolder = new AVObject(name);// 构建对象
                        if (list.size() == 0) {
                            affixionPersonalHistory(todoFolder, objectId);
                        } else {
                            String select = "update " + name + " set isFresh=1 where  objectId= " + "'" + list.get(0).getObjectId() + "'";
                            AVQuery.doCloudQueryInBackground(select, new CloudQueryCallback<AVCloudQueryResult>() {
                                @Override
                                public void done(AVCloudQueryResult avCloudQueryResult, AVException e) {
                                    if (e == null) {
                                    } else {
                                        e.printStackTrace();
                                    }
                                }
                            });
                        }
                    } else {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    //          将商品添加进用户的历史浏览表
    @Override
    public void affixionPersonalHistory(AVObject aVObject, String proObject) {
        if (entity != null) {
            aVObject.put("proId", proObject);
            aVObject.put("pro", AVObject.createWithoutData("ClassifyGoodsThird", proObject));
            aVObject.saveInBackground();// 保存到服务端

        }
    }
}